package com.xiaomai.msmservice.controller;


import com.xiaomai.commonutil.R;
import com.xiaomai.msmservice.service.MsmService;
import com.xiaomai.msmservice.utils.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@EnableDiscoveryClient

public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R sendCode(@PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
                return R.ok();
        }

        code = RandomUtil.getFourBitRandom();
        Map<String,Object> map = new HashMap<>();
       boolean flag =  msmService.send(code,phone);
       if (flag){
           redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
           return R.ok();
       }else{
           return R.error().message("短信发送失败");
       }

    }
}
